package com.sx213.controller;

import com.sx213.utils.TokenProccessorUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * @Author liliang
 * @Description:
 * @Date 18/1/8 上午10:24
 */
@Controller
public class DemoController {

    @RequestMapping("/index")
    public String fromPage(HttpServletRequest request) {
        String token = TokenProccessorUtil.getInstance().makeToken();
        request.getSession().setAttribute("token",token);
        System.out.println("在FormServlet中生成的token："+token);
        return "index";
    }

    @RequestMapping(value = "/demo", method = RequestMethod.POST)
    public void demo(HttpSession session, @RequestParam("username") String username,@RequestParam("token") String token) {
        String serverToken = (String) session.getAttribute("token");
        boolean b = isRepeatSubmit(token, serverToken);
        if (b) {
            System.out.println("qingbuychongfutijiao========");
            return;
        }
        session.removeAttribute("token");
        System.out.println("dddddd :==" + username);
    }


    /**
     * 判断客户端提交上来的令牌和服务器端生成的令牌是否一致
     * @param client_token
     * @param server_token
     * @return true 用户重复提交了表单 false 用户没有重复提交表单
     */

    private boolean isRepeatSubmit(String client_token, String server_token) {
        //1、如果用户提交的表单数据中没有token，则用户是重复提交了表单
        if (client_token == null) {
            return true;
        }
        //取出存储在Session中的token
        //2、如果当前用户的Session中不存在Token(令牌)，则用户是重复提交了表单
        if (server_token == null) {
            return true;
        }
        //3、存储在Session中的Token(令牌)与表单提交的Token(令牌)不同，则用户是重复提交了表单
        if (!client_token.equals(server_token)) {
            return true;
        }
        return false;
    }
}
